<?php

/**
 * 短信发送
 */
use think\Config;
class Sms {

    protected $_sms;
    protected $_error;
    protected $_setting = array();
    protected $_type = '';
    protected $_smsSendType = array('captcha', 'notice', 'other');

    public function __construct($name) {

        include_once  dirname(__FILE__)."/qscmslib/sms/{$name}/{$name}.class.php";
        $this->_setting = array('appkey' => Config::get('yimei.appkey'), 'secretKey' => Config::get('yimei.secretKey'), 'signature' => '');
        $class = $name.'_sms';
        $this->_sms = new $class($this->_setting);
    }

    public function sendTemplateSMS($type = 'captcha', &$option) {
        if (!$this->_setting) {
            $this->_error = '请配置短信参数！';
            return false;
        }
        if (!in_array($type, $this->_smsSendType)) {
            $this->_error = '请选择正确的短信发送类型！';
            return false;
        }
        if (!$option['mobile']) {
            $this->_error = '请填写手机号码！';
            return false;
        }

        if (!$this->_mobileBreak($option['mobile'])) {
            $this->_error = '手机号格式不合法！';
            return false;
        }
        if (false === $result = $this->_sms->sendTemplateSMS($type, $option)) {
            $this->_error = $this->_sms->getError();
            return false;
        }
        return $result;
    }

    /**
     * [手机批量验证]
     * @param  [string] $data ['15865441236,13652415865']
     * @return [boolean]
     */
    protected function _mobileBreak($data = '') {
        $mobile = explode(',', $data);
        foreach ($mobile as $val) {
            if (false === $this->fieldRegex($val, 'mobile'))
                return false;
        }
        return true;
    }

    public function getError() {
        return $this->_error;
    }

    private function fieldRegex($value, $rule) {
        $validate = array(
            'require' => '/.+/',
            'email' => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',
            'mobile' => '/^(13|15|14|17|18)\d{9}$/',
            'tel' => '/^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})(-(\\d{3,}))?$/',
            'url' => '/^http(s?):\/\/(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?$/',
            'currency' => '/^\d+(\.\d+)?$/',
            'number' => '/^\d+$/',
            'zip' => '/^\d{6}$/',
            'integer' => '/^[-\+]?\d+$/',
            'double' => '/^[-\+]?\d+(\.\d+)?$/',
            'english' => '/^[A-Za-z]+$/',
            'img' => '(.*)\\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$/',
            'in' => '/^(\d{1,10},)*(\d{1,10})$/',
            'qq' => '/^[1-9]*[1-9][0-9]*$/'
        );
        // 检查是否有内置的正则表达式
        if (isset($validate[strtolower($rule)]))
            $rule = $validate[strtolower($rule)];
        return preg_match($rule, $value) === 1;
    }

}
